﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using System.ComponentModel;
using Microsoft.ConfigurationManagement.ManagementProvider;
using Microsoft.ConfigurationManagement.ManagementProvider.WqlQueryEngine;

using System.Text.RegularExpressions;


namespace TimNilimaaConsulting.DeploymentWeb.Controllers
{
    public class ComputerController : Controller
    {
        private SCCM_Connector cm_connector = new SCCM_Connector();

        //
        // GET: /Computer/
        public ActionResult Index()
        {
            WqlConnectionManager connection = cm_connector.Connect(System.Configuration.ConfigurationManager.AppSettings["CMserver"]);

            List<TimNilimaaConsulting.DeploymentWeb.ViewModels.ListComputerViewModel> Computers = new List<TimNilimaaConsulting.DeploymentWeb.ViewModels.ListComputerViewModel>();

            string query = "Select * FROM SMS_R_System";

            try
            {
                IResultObject listOfComputers = connection.QueryProcessor.ExecuteQuery(query);

                foreach (IResultObject resource in listOfComputers)
                {
                    ViewModels.ListComputerViewModel computer = new ViewModels.ListComputerViewModel();
                    computer.Name = resource["Name"].StringValue;
                    computer.ResourceId = (UInt32)resource["ResourceId"].IntegerValue;
                    computer.MacAddresses = resource["MacAddresses"].StringArrayValue;
                    Computers.Add(computer);
                }
            }
            catch
            {
            }
            
            return View(Computers);
        }

        //
        // GET: /Computer/Details/5
        public ActionResult Details(int id)
        {
            return View();
        }

        public ActionResult Error()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Error([Bind(Include = "Message")] string message)
        {
            //return RedirectToAction("Error", new { Message = message });
            return View(message);
        }


        //
        // GET: /Computer/Create
        public ActionResult Create()
        {

            IList<string> colIds = System.Configuration.ConfigurationManager.AppSettings["OSDCollections"].Split(';');
            List<Models.Collection> collections = new List<Models.Collection>();
            if (colIds.Count > 0)
            {
                WqlConnectionManager connection = cm_connector.Connect(System.Configuration.ConfigurationManager.AppSettings["CMserver"]);

                foreach (string colId in colIds)
                {

                    try
                    {
                        IResultObject cmcollection = connection.GetInstance(string.Format("SMS_Collection.CollectionID='{0}'", colId));
                        Models.Collection collection = new Models.Collection();
                        collection.CollectionId = cmcollection["CollectionID"].StringValue;
                        collection.CollectionName = cmcollection["Name"].StringValue;
                        collections.Add(collection);
                    }
                    catch (Exception ex)
                    {

                    }
                }
            }


            ViewBag.Collections = collections;


            return View();
        }

        //
        // POST: /Computer/Create
        [HttpPost]
        public ActionResult Create([Bind(Include = "Name,MACAddress")] ViewModels.NewComputerViewModel computer, string CollectionId)
        {
            try
            {
                WqlConnectionManager connection = cm_connector.Connect(System.Configuration.ConfigurationManager.AppSettings["CMserver"]);




                Dictionary<string, object> inParams = new Dictionary<string, object>();
                inParams.Add("NetbiosName", computer.Name);
                inParams.Add("SMBIOSGUID", "");

                string macAddress = computer.MacAddress;

                Match success = Regex.Match(macAddress, @"/^([0-9a-f]{1,2}[\.:-]){5}([0-9a-f]{1,2})$/i");
                if (success.Success == false)
                {
                    macAddress = macAddress.Trim(':', '-', '.');
                    success = Regex.Match(macAddress, @"/^([0-9a-f]{1,2}[\.:-]){5}([0-9a-f]{1,2})$/i");
                    if (macAddress.Length == 17)
                    {
                        macAddress = macAddress.Replace('.', ':').Replace('-', ':');
                    }

                    if (macAddress.Length == 12)
                    {
                        var regex = "(.{2})(.{2})(.{2})(.{2})(.{2})(.{2})";
                        var replace = "$1:$2:$3:$4:$5:$6";
                        macAddress = Regex.Replace(macAddress, regex, replace);
                    }
                }


                inParams.Add("MACAddress", macAddress);
                inParams.Add("OverwriteExistingRecord", false);

                IResultObject outParams = connection.ExecuteMethod(
                    "SMS_Site",
                    "ImportMachineEntry",
                    inParams);


                try
                {
                    IResultObject collection = connection.GetInstance(String.Format("SMS_Collection.collectionId='{0}'", CollectionId));
                    collection.Get();
                    IResultObject collectionRule = connection.CreateEmbeddedObjectInstance("SMS_CollectionRuleDirect");
                    collectionRule["ResourceClassName"].StringValue = "SMS_R_System";
                    collectionRule["ResourceID"].IntegerValue = outParams["ResourceID"].IntegerValue;

                    Dictionary<string, object> inParams2 = new Dictionary<string, object>();
                    inParams2.Add("collectionRule", collectionRule);

                    collection.ExecuteMethod("AddMembershipRule", inParams2);

                    string limitingCollectionId = collection["LimitToCollectionID"].StringValue;

                    do
                    {
                        IResultObject limitingCollection = connection.GetInstance(string.Format("SMS_Collection.collectionId='{0}'", limitingCollectionId));
                        limitingCollection.Get();

                        collectionRule = connection.CreateEmbeddedObjectInstance("SMS_CollectionRuleDirect");
                        collectionRule["ResourceClassName"].StringValue = "SMS_R_System";
                        collectionRule["ResourceID"].IntegerValue = outParams["ResourceID"].IntegerValue;

                        inParams2 = new Dictionary<string, object>();
                        inParams2.Add("collectionRule", collectionRule);

                        limitingCollection.ExecuteMethod("AddMembershipRule", inParams2);

                        limitingCollectionId = limitingCollection["LimitToCollectionID"].StringValue;
                    } while (limitingCollectionId != "SMS00001");

                    try
                    {
                        IResultObject collection_All_Systems = connection.GetInstance("SMS_Collection.collectionId='SMS00001'");
                        collection_All_Systems.ExecuteMethod("RequestRefresh", null);

                        collection.Get();
                        limitingCollectionId = collection["LimitToCollectionID"].StringValue;
                        do
                        {
                             IResultObject limitingCollection = connection.GetInstance(string.Format("SMS_Collection.collectionId='{0}'", limitingCollectionId));
                             limitingCollection.Get();
                             limitingCollection.ExecuteMethod("RequestRefresh", null);
                             limitingCollectionId = limitingCollection["LimitToCollectionID"].StringValue;
                        } while (limitingCollectionId != "SMS00001");

                        collection.ExecuteMethod("RequestRefresh", null);
                    }
                    catch
                    {

                    }
                }
                catch
                {

                }


                return RedirectToAction("Index");
            }
            catch (Exception ex)
            {
                return RedirectToAction("Error", new { Message = ex.Message  });
                //return View();
            }

        }

        //
        // GET: /Computer/Edit/5
        public ActionResult Edit(int id)
        {
            return View();
        }

        //
        // POST: /Computer/Edit/5
        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Computer/Delete/5
        public ActionResult Delete(int id)
        {
            return View();
        }

        //
        // POST: /Computer/Delete/5
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}
